package com.yindian.cos.easy.security.authentication.login.social.qq;

import com.yindian.cos.easy.security.authentication.login.social.core.AbstractAccessTokenFactory;
import com.yindian.cos.easy.security.authentication.login.social.core.AccessToken;
import com.yindian.cos.easy.security.constant.ProviderName;
import com.yindian.cos.easy.security.exception.AccessTokenException;
import com.yindian.cos.easy.security.properties.EasySecurityProperties;
import com.yindian.cos.easy.security.properties.QqProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * qq获取access_token默认实现
 *
 * @author zhangchuanhao
 * @create 2018/11/20
 */
public class QqAccessTokenFactory extends AbstractAccessTokenFactory {

    private final EasySecurityProperties easySecurityProperties;

    private final RestTemplate restTemplate;

    public QqAccessTokenFactory(EasySecurityProperties easySecurityProperties, RestTemplate restTemplate) {
        this.easySecurityProperties = easySecurityProperties;
        this.restTemplate = restTemplate;
    }

    @Override
    public AccessToken getAccessToken(String code) {
        try {
            QqProperties qqProperties = easySecurityProperties.getQq();
            String url = qqProperties.getAccessTokenUrl();
            url += "?grant_type=" + qqProperties.getGrantType();
            url += "&client_id=" + qqProperties.getAppId();
            url += "&client_secret=" + qqProperties.getAppSecret();
            url += "&code=" + code;

            String redirectUrl = qqProperties.getDomain() + qqProperties.getRedirectUri().trim();
            url += "&redirect_uri=" + redirectUrl;

            String result = restTemplate.getForObject(url, String.class);
            String accessTokenStr = null;
            Map<String, Object> map = new HashMap<>();
            if (StringUtils.contains(result, "access_token")) {
                String[] params = result.split("&");
                for (String param : params) {
                    String[] info = param.split("=");
                    if ("access_token".equals(info[0])) {
                        accessTokenStr = info[1];
                    } else {
                        map.put(info[0], info[1]);
                    }
                }
            } else {
                throw new AccessTokenException(ProviderName.QQ + "登录获取access_token失败", result);
            }
            AccessToken accessToken = new AccessToken(accessTokenStr, map);
            return accessToken;
        } catch (AccessTokenException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new AccessTokenException(ProviderName.QQ + "登录获取access_token失败", ex.getCause());
        }
    }
}
